﻿using Liang.DataBase.BLL;
using Liang.DataBase.Model.Entity;
using Liang.DataBase.Tools;
using Liang.UI;
using Liang.UI.Enums;
using Liang.Resource;
using Sunisoft.IrisSkin;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Liang.DataBase.Helper;

namespace Client
{
    public partial class MainFrm : Form
    {
        static MainFrm mainFrm = null;

        /// <summary>
        /// 二级菜单窗口
        /// </summary>
        FrmMainTool frmMainTool = null;

        /// <summary>
        /// 当前用户拥有的模块（一级菜单）
        /// <para>注意：一级菜单下的二级菜单，可能不在用户权限内</para>
        /// </summary>
        public static List<sys_module> moduleSet = new List<sys_module>();

        /// <summary>
        /// 当前用户拥有的功能（二级菜单）
        /// </summary>
        public static List<sys_app> AppSet = new List<sys_app>();

        private static SkinEngine skin = null;

        bool beginMove = false;
        int currentXPosition;
        int currentYPosition;

        public MainFrm()
        {
            InitializeComponent();
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            initModule();

            if (this.toolBar1.Items.Count == 0)
            {
                return;
            }

            if (moduleSet.Count > 0)
            {
                frmMainTool = new FrmMainTool();
                frmMainTool.SetSubMenu(moduleSet[0]);
                frmMainTool.Show(this.dockPanel, DockState.DockLeft);
                this.dockPanel.DockLeftPortion = 0.20;
            }

            logon_name_label.Text = "欢迎您：" + UserManager.loginedUser.name;

            this.Text = Liang.Model.Const.PROJECT_NAME;
            this.title_label.Text = Liang.Model.Const.PROJECT_NAME;
            this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
            this.WindowState = FormWindowState.Maximized;

            DockPaneStripGradient dpsg = new DockPaneStripGradient();
            dpsg.DockStripGradient.StartColor = ColorTranslator.FromHtml("#0061E3");
            dpsg.DockStripGradient.EndColor = ColorTranslator.FromHtml("#0061E3");
            dpsg.ActiveTabGradient.StartColor = ColorTranslator.FromHtml("#0061E3");
            dpsg.ActiveTabGradient.EndColor = SystemColors.ControlLightLight;
            this.dockPanel.Skin.DockPaneStripSkin.DocumentGradient = dpsg;

            DockPaneStripToolWindowGradient dpstwg = new DockPaneStripToolWindowGradient();
            dpstwg.ActiveCaptionGradient.StartColor = ColorTranslator.FromHtml("#0061E3");
            dpstwg.ActiveCaptionGradient.EndColor = ColorTranslator.FromHtml("#0061E3");
            dpstwg.InactiveCaptionGradient.StartColor = ColorTranslator.FromHtml("#0061E3");
            dpstwg.InactiveCaptionGradient.EndColor = ColorTranslator.FromHtml("#0061E3");
            this.dockPanel.Skin.DockPaneStripSkin.ToolWindowGradient = dpstwg;

            // 默认加载欢迎首页
            FrmHome frmHome = new FrmHome();
            frmHome.BackColor = Color.White;
            // 将子窗体加入MDI父窗体
            frmHome.MdiParent = this;
            frmHome.CloseButton = false;
            frmHome.WindowState = FormWindowState.Maximized;
            frmHome.Show(this.dockPanel);
            frmHome.Focus();
            frmHome.BringToFront();
        }

        public static MainFrm GetMainForm()
        {
            if (mainFrm == null)
            {
                mainFrm = new MainFrm();

                // 初始化，显示登陆对话框
                Form formLogin = new FrmLogin();
                formLogin.ShowDialog();
            }

            return mainFrm;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        public DockContent ShowContent(string appName/*, Type formType*/)
        {
            DockContent frm = FindDocument(appName);
            if (frm == null)
            {
                string strTemp = GetAppUrlByName(appName);
                if (string.IsNullOrEmpty(strTemp))
                {
                    return null;
                }
                string[] strSplit = strTemp.Split('.');
                string strAssemblyName = strSplit[0];
                Assembly assembly = Assembly.Load(strAssemblyName);
                Type typForm = assembly.GetType(strTemp);
                Object mdiChild = typForm.InvokeMember(
                    null,
                    BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
                    null, null, null);

                if (mdiChild != null)
                {
                    frm = mdiChild as DockContent;
                    frm.BackColor = Color.White;
                    // 将子窗体加入MDI父窗体
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                }
            }

            if (null != frm)
            {
                frm.Show(this.dockPanel);
                frm.Focus();
                frm.BringToFront();
            }

            //closeFrm();//单页签显示
            return frm;
        }

        public static void initSkin()
        {
            skin = new SkinEngine(mainFrm);
            //            EntityManager<Config> configEntityManager = new EntityManager<Config>();
            //            List<Config> list = configEntityManager.FindAll();
            //            Config c = list[0];
            byte[] bs = AssemblyHelper.GetSkinsUrl("KeyerResource", "Skins.office2007.ssk");
            MemoryStream memoryStream = new MemoryStream(bs);
            skin.SkinStream = memoryStream;
            skin.TitleFont = new System.Drawing.Font("微软雅黑", 10F);
            skin.Active = true;
        }

        /// <summary>
        /// 加载当前用户拥有的一级菜单
        /// </summary>
        void initModule()
        {
            sys_user user = UserManager.loginedUser;

            if (user == null)
            {
                return;
            }

            // 遍历加载用户所有权限包含的app
            foreach (sys_role item in user.roles)
            {
                // 遍历权限包含的app
                IEnumerable<sys_app> tmp = item.apps.ToList();
                // 用Union是为了去除重复的
                AppSet = AppSet.Union(tmp).ToList();
            }

            // 加载所有module包含的app
            ModuleBLL moduleBLL = new ModuleBLL();
            IEnumerable<sys_module> moduleList = moduleBLL.FindAll();

            IEnumerable<sys_app> moduleApps = new List<sys_app>();
            foreach (sys_module item in moduleList)
            {
                List<sys_app> tmp = item.apps.ToList();
                moduleApps = moduleApps.Union(tmp);
            }

            // 筛选模块
            // 条件1：app 属于用户权限
            // 条件2：app 属于某个模块
            bool yes = false;
            foreach (sys_module item in moduleList)
            {
                yes = false;

                foreach (sys_app appItem in item.apps)
                {
                    IEnumerable<sys_app> tmp = AppSet.Where(q => q.appId.Equals(appItem.appId));

                    if (0 < tmp.Count())
                    {
                        yes = true;
                        break;
                    }
                }

                if (yes)
                {
                    // 添加到 moduleSet，并且创建一级菜单的按钮
                    moduleSet.Add(item);
                    ToolItem t = new ToolItem();
                    t.Tag = item;
                    t.Image = AssemblyHelper.GetImage("KeyerResource", item.imgUrl);
                    this.toolBar1.Items.Add(t);
                }
            }
        }

        /// <summary>
        /// 页面容器Dockpanl加载from
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        DockContent FindDocument(string text)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.DockingMdi)
            {
                foreach (Form form in MdiChildren)
                {
                    if (form.Text == text)
                    {
                        return form as DockContent;
                    }
                }
                return null;
            }
            else
            {
                foreach (DockContent content in dockPanel.Documents)
                {
                    if (content.DockHandler.TabText == text)
                    {
                        return content;
                    }
                }
                return null;
            }
        }

        /// <summary>
        /// 根据功能id获取功能url
        /// </summary>
        /// <param name="strAppId"></param>
        /// <returns></returns>
        /// <example>
        /// <c>string strAppUrl = GetAppUrlById("FA6DB1D9-09E9-4CAB-9745-609D42C90D39");</c>
        /// 这里，strAppUrl的值即为：Liang.FrmPerson
        /// </example>
        private string GetAppUrlById(string strAppId)
        {
            string strTemp = string.Empty;

            foreach (sys_module m in moduleSet)
            {
                sys_app app = m.apps.Where(q => q.appId.ToString().Equals(strAppId)).FirstOrDefault();
                if (null != app)
                {
                    strTemp = app.appUrl;
                    break;
                }
            }

            return strTemp;
        }

        /// <summary>
        /// 根据功能名获取功能url
        /// </summary>
        /// <param name="strAppName"></param>
        /// <returns></returns>
        private string GetAppUrlByName(string strAppName)
        {
            string strTemp = string.Empty;

            foreach (sys_module m in moduleSet)
            {
                sys_app app = m.apps.Where(q => q.name.Equals(strAppName)).FirstOrDefault();
                if (null != app)
                {
                    strTemp = app.appUrl;
                    break;
                }
            }

            return strTemp;
        }

        /// <summary>
        /// 关闭其他窗体
        /// </summary>
        void closeFrm()
        {
            DockContentCollection contents = dockPanel.Contents;
            int num = 0;
            while (num < contents.Count)
            {
                if (contents[num].DockHandler.DockState == DockState.Document && dockPanel.ActiveContent != contents[num])
                {
                    contents[num].DockHandler.Hide();
                }
                else
                {
                    num++;
                }
            }
        }

        private void bottom_panel_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics, bottom_panel.ClientRectangle,
            Color.Black, 0, ButtonBorderStyle.Solid, //左边
            ColorTranslator.FromHtml("#005BE1"), 3, ButtonBorderStyle.Solid, //上边
            Color.DimGray, 0, ButtonBorderStyle.Solid, //右边
            Color.DimGray, 0, ButtonBorderStyle.Solid);//底边
        }

        //private void hblhgsc_label_Paint(object sender, PaintEventArgs e)
        //{
        //    ControlPaint.DrawBorder(e.Graphics, hblhgsc_label.ClientRectangle,
        //    Color.Black, 0, ButtonBorderStyle.Solid, //左边
        //    ColorTranslator.FromHtml("#005BE1"), 3, ButtonBorderStyle.Solid, //上边
        //    Color.DimGray, 0, ButtonBorderStyle.Solid, //右边
        //    Color.DimGray, 0, ButtonBorderStyle.Solid);//底边
        //}

        //private void version_label_Paint(object sender, PaintEventArgs e)
        //{
        //    ControlPaint.DrawBorder(e.Graphics, version_label.ClientRectangle,
        //    ColorTranslator.FromHtml("#CCE9F7"), 0, ButtonBorderStyle.Solid, //左边
        //    ColorTranslator.FromHtml("#005BE1"), 3, ButtonBorderStyle.Solid, //上边
        //    Color.DimGray, 0, ButtonBorderStyle.Solid, //右边
        //    Color.DimGray, 0, ButtonBorderStyle.Solid);//底边
        //}

        private void sysTime_Tick(object sender, EventArgs e)
        {
            this.nowTime_label.Text = string.Format("{0} {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek));
        }

        private void toolBar1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = ((Liang.UI.ToolBar)sender).SelectedIndex;
            frmMainTool.Hide();
            frmMainTool = new FrmMainTool();
            frmMainTool.SetSubMenu(moduleSet[index]);
            frmMainTool.Show(this.dockPanel, DockState.DockLeft);
        }

        private void ImageButton_Calc_Click(object sender, EventArgs e)
        {
            // 计算器
            Process p = new Process();
            p.StartInfo.FileName = "calc.exe";
            p.Start();
        }

        private void ImageButton_Help_Click(object sender, EventArgs e)
        {
            // 帮助
            MessageBoxEx.Show(this, "湖北科尔软件开发有限公司 \n 联系电话:6489788", "帮助", MessageBoxIconEx.Information, MessageBoxButtonsEx.OK);
        }

        private void ImageButton_Logout_Click(object sender, EventArgs e)
        {
            // 注销
            if (MessageBoxEx.Show(this, "确定注销吗？", "提示", MessageBoxIconEx.Question, MessageBoxButtonsEx.OKCancel) == DialogResult.OK)
            {
                Process sprs = new Process();
                sprs.StartInfo.FileName = Application.ExecutablePath.Trim();
                sprs.Start();
                Process.GetCurrentProcess().Kill();
            }
        }

        private void imageButton_editPassword_Click(object sender, EventArgs e)
        {
            // 修改密码
            FormEditPassword form = new FormEditPassword();
            form.ShowDialog();
        }

        private void pictureBox_MinimumSize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void pictureBox_MaximumSize_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.FormBorderStyle = FormBorderStyle.None;
                this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void pictureBox_CloseWindow_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region 鼠标控制拖动窗口
        private void myPanel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                beginMove = true;
                currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标
                currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标
            }
        }

        private void myPanel1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                currentXPosition = 0; //设置初始状态
                currentYPosition = 0;
                beginMove = false;
            }
        }

        private void myPanel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (beginMove)
            {
                this.Left += MousePosition.X - currentXPosition;//根据鼠标x坐标确定窗体的左边坐标x
                this.Top += MousePosition.Y - currentYPosition;//根据鼠标的y坐标窗体的顶部，即Y坐标
                currentXPosition = MousePosition.X;
                currentYPosition = MousePosition.Y;
            }
        }
        #endregion
    }
}
